<template>
  <el-card>
    <el-form ref="addForm" :model="addData" :rules="rules" label-width="100px" >
      <el-form-item prop="rolename" label="角色名称">
        <el-input
          v-model="addData.rolename"
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="menus" label="角色权限">
        <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="defaultProps"
          ref="tree"
          :default-checked-keys="addData.menus.split(',')"
        ></el-tree>
      </el-form-item>
      <el-form-item prop="status" label="状态">
        <el-radio-group v-model="addData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即更新</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getMenuList } from "../../request/menu";
import { getRoleById } from "../../request/role";
export default {
  data() {
    const menuValidate = (rule, value, callback) => {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      if (checkedKeys.length === 0) {
        callback(new Error("请选择操作权限"));
      }
      callback();
    };
    return {
      addData: {
        rolename: "",
        menus: "",
        status: 1,
      },
      rules: {
        rolename: { required: true, message: "请输入角色名称" },
        menus: { validator: menuValidate, trigger: "blur" },
        status: { required: true, message: "请选择状态" },
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
    };
  },
  created() {
    this.getMenuList();
    this.getRoleById();
  },
  methods: {
    submitForm() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.addData.menus = this.$refs.tree.getCheckedKeys().join(",");
          const res = await this.$http.post("/api/roleedit", {
            ...this.addData,
            id: this.$router.params.id,
          });
          if (res.code == 200) {
            this.$success(res.msg);
            return this.$router.push("/role");
          }
          this.$error(res.msg);
        }
      });
    },
    async getMenuList() {
      const list = await getMenuList();
      if (list) {
        this.data = list;
      }
    },
    async getRoleById() {
      const res = await getRoleById(this.$route.params.id);
      if (res) {
        this.addData = res;
      }
    },
  },
};
</script>
<style lang='less' scoped>
.el-form {
  width: 600px;
  margin: 0 auto;
}
</style>